package com.tadpole.music.presenter.home;

import com.tadpole.music.bean.home.NoticeBean;
import com.tadpole.music.callback.BaseCallback;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.home.NoticeIView;
import com.tadpole.music.model.base.DataModel;
import com.tadpole.music.model.base.ModelToken;
import com.tadpole.music.presenter.base.BasePresenter;
import com.tadpole.music.utils.JsonParseUtil;
import com.tadpole.music.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取首页公告
 * Created By 孙岩
 * on 2020/9/18
 */
public class NoticePresenter extends BasePresenter<NoticeIView> {
    @SuppressWarnings("unchecked")
    public void getNotice() {
        String url = UrlConfig.homeNotice;
        DataModel.request(ModelToken.GET_REQUEST)
                .url(url)
                .execute(new BaseCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        try {
                            JSONObject obj = new JSONObject(data);
                            if (obj.getInt("code") == 200) {
                                JSONArray array = new JSONArray(obj.getString("data"));
                                List<NoticeBean.DataBean> list = new ArrayList<>();
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject object = new JSONObject(array.get(i).toString());
                                    NoticeBean.DataBean bean = new NoticeBean.DataBean(
                                            JsonParseUtil.getInt(object, "id"),
                                            JsonParseUtil.getStr(object, "created_at"),
                                            JsonParseUtil.getStr(object, "updated_at"),
                                            JsonParseUtil.getStr(object, "title")
                                    );
                                    list.add(bean);
                                }
                                getView().showNoticeList(list);
                            } else {
                                ToastUtils.show(obj.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        getView().showErr();
                        getView().stopRefresh();
                    }

                    @Override
                    public void onComplete() {
                        getView().stopRefresh();
                    }

                    @Override
                    public void onBefore() {

                    }
                });
    }
}
